package com.yonyou.jrmob.contacts.contact.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.yonyou.jrmob.contacts.R;
import com.yonyou.jrmob.contacts.contact.bean.ContactsVO_ct;
import com.yonyou.jrmob.contacts.contact.dbhelper.DBManager_ct;
import com.yonyou.jrmob.contacts.contact.utils.CSIMCardUtil_ct;
import com.yonyou.jrmob.contacts.contact.utils.CameraAndAlbumUtil_ct;
import com.yonyou.jrmob.contacts.contact.utils.ContactsUtil_ct;
import com.yonyou.jrmob.contacts.contact.view.BottomPopupOption;
import com.yonyou.jrmob.contacts.contact.view.dialog.MaterialDialog;
import com.yonyou.uap.um.service.ServiceCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.gkh.MAServices_gkh;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.ChangeHeadImgObserverUtilTD;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.CommonUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.MobUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.StatusBarUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.UiUtils;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import jrmob.yonyou.com.commonlib.login.bean.MAServices_lib;
import jrmob.yonyou.com.commonlib.login.bean.UserInfoLRY;

public class ContactsDetailActivity_ct extends BaseActivityMob_lib implements
        View.OnClickListener {
    private ImageView back_btn;
    private TextView contactName;
    private String cuserID;
    private TextView contactDep;
    private TextView contactPho;
    private TextView contactTel;
    private TextView contactEmail;
    private TextView contactOrg;
    private TextView contactDept;
    private ImageView messageIV;
    private ImageView phoneIV;
    private ImageView telIV;
    private ImageView emailIV;
    private ImageView iconIV;
    private String opflag = "1";//未关注
    private ContactsVO_ct contacts;
    private DBManager_ct dbmr;
    private boolean hasSIMCard;
    private ImageView more_btn_mune;
    private MorePopWindow morePopWindow;
    private ContactsUtil_ct contactsUtilCt;
    private BottomPopupOption bottomPopupOption;
    private BottomPopupOption bottomPopupOption2;
    private Dialog loadingDialog;
    private UserInfoLRY userInfo2 = null;
    private String dataString;
    private static String url = null;
    private static Uri uritempFile = null;
    final public static int REQUEST_CODE_ASK_CALL_CAMERA = 123;
    /**
     * 相机相册CODE
     **/
    public static final String IMAGE_UNSPECIFIED = "image/*";
    public static final int ALBUM_REQUEST_CODE = 1;
    public static final int CAMERA_REQUEST_CODE = 2;
    public static final int CROP_REQUEST_CODE = 4;
    public static final int CROP_REQUEST_CODE5 = 5;

    private boolean isMyself = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tempStatus = 1;
//        initActionbar();
        setContentView(R.layout.contact_detail_ct);
        initView(); // 初始化控件
        initData(); // 默认初始数据
        initListener(); // 添加监听
        StatusBarUtil.transparencyBar(this);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) findViewById(R.id.contact_detail_top_ll).getLayoutParams();
        lp.topMargin = UiUtils.getStatusBarHeight();
        findViewById(R.id.contact_detail_top_ll).setLayoutParams(lp);

//        userInfo2 = MobUtils.readObject(mShare, Constant.userInfo, UserInfo_lib.class);
        // userInfo2 = MobUtils.readObject(mShare, "UserInfo_lib", UserInfo_lib.class);
        userInfo2 = readLocationObject(Constant.userInfoLry, UserInfoLRY.class);
    }


    public void initView() {

        /*//可以将一下代码加到你的MainActivity中，或者在任意一个需要调用分享功能的activity当中
        String[] mPermissionList = new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CALL_PHONE,
                Manifest.permission.READ_LOGS,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.SET_DEBUG_APP,
                Manifest.permission.SYSTEM_ALERT_WINDOW,
                Manifest.permission.GET_ACCOUNTS};*/
        //ActivityCompat.requestPermissions(ContactsDetailActivity_ct.this, mPermissionList, 100);

        dbmr = new DBManager_ct(this);
        loadingDialog = MobUtils.createLoadingDialog(this, "加载中请稍后...");
        bottomPopupOption = new BottomPopupOption(ContactsDetailActivity_ct.this);
        bottomPopupOption.setItemText("新增联系人", "修改联系人");
        bottomPopupOption2 = new BottomPopupOption(ContactsDetailActivity_ct.this);
        bottomPopupOption2.setItemText("相册", "拍照", "查看头像");
        back_btn = (ImageView) findViewById(R.id.top_img_back);
        contactName = (TextView) findViewById(R.id.contact_sign);
        contactDep = (TextView) findViewById(R.id.contact_dep);
        contactPho = (TextView) findViewById(R.id.contact_pho);
        contactTel = (TextView) findViewById(R.id.contact_tel);
        contactEmail = (TextView) findViewById(R.id.contact_email);
        contactOrg = (TextView) findViewById(R.id.contact_org);
        contactDept = (TextView) findViewById(R.id.contact_dept);
        messageIV = (ImageView) findViewById(R.id.message_icon);
        phoneIV = (ImageView) findViewById(R.id.phone_icon);
        telIV = (ImageView) findViewById(R.id.tel_icon);
        emailIV = (ImageView) findViewById(R.id.email_icon);
        iconIV = (ImageView) findViewById(R.id.top_img_name);
        hasSIMCard = new CSIMCardUtil_ct(this).isHasSIMCard();
        more_btn_mune = (ImageView) findViewById(R.id.more_btn_mune);
        contactsUtilCt = new ContactsUtil_ct(this);

    }

    @Override
    public void initListener() {

        back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomPopupOption2.dismiss();
                finish();
            }
        });
        messageIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uri smsToUri = Uri
                        .parse("smsto:" + contactPho.getText().toString());
                Intent intent1 = new Intent(android.content.Intent.ACTION_SENDTO,
                        smsToUri);
                startActivity(intent1);
            }
        });
        phoneIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //拨打电话
                final MaterialDialog dialog1 = new MaterialDialog(ContactsDetailActivity_ct.this);
                dialog1.setTitle("拨打确认");
                dialog1.setMessage(contactName.getText().toString() + "\n" +
                        contactPho.getText().toString());
                dialog1.setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog1.dismiss();
                        if (hasSIMCard) {
                            if (contactPho.getText().toString().equals("")) {
                                //Toast.makeText(ContactsDetailActivity_ct.this,"未找到电话号码",Toast.LENGTH_SHORT).show();
                                AlertDialog.Builder builder = new AlertDialog.Builder(ContactsDetailActivity_ct.this);  //先得到构造器
                                builder.setNegativeButton("未读取到电话号码!", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        dialogInterface.dismiss();
                                    }
                                }).create().show(); //设置内容
                                return;
                            } else {
                                dbmr.querychongfu(contacts.getContactName(), contacts.getVdef(), contacts.getContactTel(), contacts.getUser_email(), contacts.getCuserId());

                                Intent intent = new Intent().setData(Uri.parse("tel:" + contactPho.getText().toString()));
                                intent.setAction(Intent.ACTION_CALL);
                                startActivity(intent);
                            }
                        } else {
                            CommonUtil.showToast(ContactsDetailActivity_ct.this, "SIM卡未插入或暂时不可用!");
                        }
                    }
                });
                dialog1.setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog1.dismiss();
                    }
                });
                dialog1.show();
            }
        });
        telIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //拨打电话
                final MaterialDialog dialog2 = new MaterialDialog(ContactsDetailActivity_ct.this);
                dialog2.setTitle("拨打确认");
                dialog2.setMessage(contactName.getText().toString() + "\n" +
                        contactTel.getText().toString());
                dialog2.setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog2.dismiss();
                        if (hasSIMCard) {
                            if (contactTel.getText().toString().equals("")) {
                                //Toast.makeText(ContactsDetailActivity_ct.this,"未找到电话号码",Toast.LENGTH_SHORT).show();
                                AlertDialog.Builder builder = new AlertDialog.Builder(ContactsDetailActivity_ct.this);  //先得到构造器
                                builder.setNegativeButton("未读取到电话号码!", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        dialogInterface.dismiss();
                                    }
                                }).create().show(); //设置内容
                                return;
                            } else {
                                //判断在数据库中是否已经存在Yes：存在，NO：不存在
                                dbmr.querychongfu(contacts.getContactName(), contacts.getVdef(), contacts.getContactTel(), contacts.getUser_email(), contacts.getCuserId());

                                Intent intent = new Intent().setData(Uri.parse("tel:" + contactTel.getText().toString()));
                                intent.setAction(Intent.ACTION_CALL);
                                startActivity(intent);
                            }
                        } else {
                            CommonUtil.showToast(ContactsDetailActivity_ct.this, "SIM卡未插入或暂时不可用!");
                        }
                    }
                });
                dialog2.setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog2.dismiss();
                    }
                });
                dialog2.show();
            }
        });
        emailIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uri uri = Uri.parse("mailto:" + contactEmail.getText().toString());
                Intent intent4 = new Intent(Intent.ACTION_SENDTO, uri);
                try {
                    startActivity(intent4);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                    showToast("未安装邮件应用！");
                }
            }
        });
        more_btn_mune.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (morePopWindow != null) {
                    morePopWindow.showPopupWindow(more_btn_mune);
                }
            }
        });
        iconIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UserInfoLRY userInfoLRY = readLocationObject(Constant.userInfoLry, UserInfoLRY.class);
                if (userInfoLRY.getUser_id().equals(cuserID) || isMyself) {
                    bottomPopupOption2.showPopupWindow();
                } else {
                    Intent intent = new Intent(ContactsDetailActivity_ct.this, HeadImageActivity_ct.class);
                    intent.putExtra("url", url);
                    startActivity(intent);
                }
            }
        });
        bottomPopupOption2.setItemClickListener(new BottomPopupOption.onPopupWindowItemClickListener() {
            @Override
            public void onItemClick(int position) {
                switch (position) {
                    case 0:
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType("image/*");//相片类型
                        startActivityForResult(intent, openPhotos);

                        break;
                    case 1:
                        int checkCallPhonePermission = ContextCompat.checkSelfPermission(ContactsDetailActivity_ct.this, Manifest.permission.CAMERA);
                        if (Build.VERSION.SDK_INT >= 23 && checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                            requestPermission(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_ASK_CALL_CAMERA);
                            return;
                        }
                        Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        Uri uri;
                        File file = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
                        try {
                            if (!file.exists())
                                file.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if (isSurpass7Version()) {
//                            uri = FileProvider.getUriForFile(ContactsDetailActivity_ct.this, "com.yonyou.jrmob.fileprovider", new File(Environment.
//                                    getExternalStorageDirectory(), "temp.jpg"));
//                            intent2.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //这一步很重要。给目标应用一个临时的授权。
                            // 适配android 7
                            ContentValues contentValues = new ContentValues(1);
                            contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
                            uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                        } else {
                            uri = Uri.fromFile(file);
                        }
                        intent2.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        uritempFile = uri;
                        startActivityForResult(intent2, CAMERA_REQUEST_CODE);

                        break;
                    case 2:
                        Intent intent3 = new Intent(ContactsDetailActivity_ct.this, HeadImageActivity_ct.class);
                        intent3.putExtra("url", url);
                        startActivity(intent3);
                        break;
                }
                bottomPopupOption2.dismiss();
            }
        });

    }

    /***
     * 调用后台服务
     */
    private void callService() {

        JSONObject json = new JSONObject();
        try {
            json.put("transtype", Constant.TRANSTYPE_CONTACT_INFO);
            json.put("contact_id", cuserID);
            json.put("tenant_id", getUserInfoLRY().getTenant_id());
            json.put("uuidToken", Constant.TOKEN);
            if (!CommonUtil.isNetworkConnected(this)) {
                CommonUtil.showToast(this, "当前网络不可用,请检查!");
                return;
            }

            if (null != loadingDialog && !loadingDialog.isShowing()) {
                loadingDialog.show();
            }

            MAServices_gkh.callMACommonService(this, new ServiceCallback() {
                @Override
                public void execute(JSONObject json1) {
                    LogUtils.e("联系人数据：" + json1.toString());
                    JSONObject jsObject;
                    JSONObject jsArray;
                    try {
                        jsObject = (JSONObject) json1.opt("result");
                        Object obj = jsObject.opt("retflag");
                        // 有错误的时候
                        if (null != obj && obj.toString().trim().equals("1")) {
                            if (loadingDialog != null && loadingDialog.isShowing()) {
                                loadingDialog.dismiss();
                            }
                            String msg = jsObject.optString("msg").toString().trim();
                            showMessage(msg);
                            if (msg.contains("请重新登录")) {
                                turnToLoginActivity(ContactsDetailActivity_ct.this);
                            }
                            return;
                        }
                        jsArray = (JSONObject) jsObject.get("contactsInfo");
                        contacts = new ContactsVO_ct();
                        contacts.setContactName(jsArray.optString("user_name"));
                        contacts.setVdef(jsArray.optString("user_mobilephone"));
                        contacts.setConcernstatus(jsArray.optString("concernstatus"));
                        contacts.setContactTel(jsArray.optString("user_telephone"));
                        contacts.setUser_email(jsArray.optString("user_email"));
                        contacts.setCuserId(jsArray.optString("cuserid"));
                        contacts.setGroupName(jsArray.optString("groupname"));
                        contacts.setOrgName(jsArray.optString("orgname"));

                        url = jsArray.optString("avatar_url", "").trim();

                        if (contacts.getConcernstatus().equals("0")) {
                            opflag = "1";
                        } else {
                            opflag = "0";
                        }
                        //获得opflag后实例化popwindow对象
                        morePopWindow = new MorePopWindow(ContactsDetailActivity_ct.this);

                        contactDep.setText(contacts.getGroupName());
                        contactPho.setText(contacts.getVdef());
                        contactTel.setText(contacts.getContactTel());
                        contactEmail.setText(contacts.getUser_email());
                        contactOrg.setText(contacts.getOrgName());
                        contactDept.setText(contacts.getGroupName());

                        if (loadingDialog != null && loadingDialog.isShowing()) {
                            loadingDialog.dismiss();
                        }
                        setIcon();

                    } catch (JSONException e1) {
                        e1.printStackTrace();
                        if (loadingDialog != null && loadingDialog.isShowing()) {
                            loadingDialog.dismiss();
                        }
                        showMessage(e1);
                    }
                }

                @Override
                public void error(String arg0, String arg1) {
                    if (loadingDialog != null && loadingDialog.isShowing()) {
                        loadingDialog.dismiss();
                    }
                    // 设置登录按钮可用性(登录请求后台有反应后可用)
                    Toast.makeText(ContactsDetailActivity_ct.this, arg0 + arg1,
                            Toast.LENGTH_LONG).show();
                }
            }, json,MAServices_gkh.initMaRequestUrl());

        } catch (Exception e) {
            // 设置登录按钮可用性(登录请求后台有反应后可用)
            Log.e("mmmm", e + "");
            e.printStackTrace();
            if (loadingDialog != null && loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }
            showMessage(e);
        }


    }

    void setIcon() {
        if (isMyself)
            url = contacts.getPerson_logo();

        if (TextUtils.isEmpty(url)) {
        } else {
           /* Glide.with(ContactsDetailActivity_ct.this).load(url)
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .transform(new GlideCircleTransform_ct(ContactsDetailActivity_ct.this))
                    .into(iconIV);*/
        }
        LogUtils.e("url = " + url);

    }

    /***
     * 调用后台服务
     *
     * @param
     */
    private void setAttenService() {

        JSONObject json = new JSONObject();
        try {
            // opflag,user_id,cuserid
            json.put("transtype", "concerncontact");
            json.put("user_id", getUserInfo().getUserid());
            json.put("sessionkey", getUserInfo().getSessionkey());
            json.put("cuserid", cuserID);
            json.put("opflag", opflag);
            if (!CommonUtil.isNetworkConnected(this)) {
                CommonUtil.showToast(this, "当前网络不可用,请检查!");
                return;
            }
            MAServices_lib.callMACommonService(this, new ServiceCallback() {
                @Override
                public void execute(JSONObject json1) {
                    JSONObject json = (JSONObject) json1.opt("result");
                    Object obj = json.opt("retflag");
                    // 有错误的时候
                    if (null != obj && obj.toString().trim().equals("1")) {
                        String msg = json.optString("msg").toString().trim();
                        showMessage(msg);
                        if (msg.contains("请重新登录")) {
                            turnToLoginActivity(ContactsDetailActivity_ct.this);
                        }
                        return;
                    }
                }

                @Override
                public void error(String arg0, String arg1) {
                    Toast.makeText(ContactsDetailActivity_ct.this, arg0 + arg1,
                            Toast.LENGTH_LONG).show();
                }
            }, json);

        } catch (Exception e) {
            Log.e("mmmm", e + "");
            e.printStackTrace();
        }

    }

    public void backMethod() {
    }

    @Override
    public void initData() {
        contactName.setText(getIntent().getExtras().getString("name"));
        //iconIV.setText(subUtil(getIntent().getExtras().getString("name").trim()));
        cuserID = getIntent().getExtras().getString("cuserId");
        LogUtils.e(cuserID);
        if (!"isMyself".equals(cuserID)) {
            callService();
        } else {
            isMyself = true;
            Bundle bundle = getIntent().getExtras();
            contacts = (ContactsVO_ct) bundle.getSerializable("contact");

            //获得opflag后实例化popwindow对象
            morePopWindow = new MorePopWindow(ContactsDetailActivity_ct.this);

            contactDep.setText(contacts.getGroupName());
            contactPho.setText(contacts.getVdef());
            contactTel.setText(contacts.getContactTel());
            contactEmail.setText(contacts.getUser_email());
            contactOrg.setText(contacts.getOrgName());
            contactDept.setText(contacts.getGroupName());

            messageIV.setVisibility(View.GONE);
            phoneIV.setVisibility(View.GONE);
            telIV.setVisibility(View.GONE);
            emailIV.setVisibility(View.GONE);
            setIcon();
        }

    }

    public String subUtil(String name) {
        String sbNameString = "";
        if (null != name && name.length() > 2) {
            sbNameString = name.substring(name.length() - 2);
        } else {
            sbNameString = name;
        }
        return sbNameString;
    }

    //选择弹窗
    class MorePopWindow extends PopupWindow {
        private View conentView;
        private LinearLayout att_ll;
        private TextView att_text;
        private LinearLayout save_contact;
        private LinearLayout share_contact;
        private ImageView att_iv;
        private LinearLayout change_number;
        private EditText edit_phone_number;
        private EditText edit_tel_number;


        public MorePopWindow(final Activity context) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            conentView = inflater.inflate(R.layout.more_pop_dialog_ct, null);
            att_ll = (LinearLayout) conentView.findViewById(R.id.att_ll);
            save_contact = (LinearLayout) conentView.findViewById(R.id.save_contact);
            share_contact = (LinearLayout) conentView.findViewById(R.id.share_contact);
            share_contact.setVisibility(View.GONE);
            att_text = (TextView) conentView.findViewById(R.id.att_text);
            att_iv = (ImageView) conentView.findViewById(R.id.att_iv);
            change_number = (LinearLayout) conentView.findViewById(R.id.change_number);

            if (userInfo2 != null && userInfo2.getTenant_id() != null && userInfo2.getTenant_id().equals(cuserID)) {
                change_number.setVisibility(View.GONE);
                att_ll.setVisibility(View.GONE);
            } else {
                change_number.setVisibility(View.GONE);
                att_ll.setVisibility(View.GONE);
            }
            setListener();
            if (opflag.equals("0")) {
                att_text.setText("关注");
                att_iv.setImageDrawable(getResources().getDrawable(R.mipmap.guanzhu_ct));
            } else {
                att_text.setText("取消关注");
                att_iv.setImageDrawable(getResources().getDrawable(R.mipmap.quguan_ct));
            }

            int h = context.getWindowManager().getDefaultDisplay().getHeight();
            int w = context.getWindowManager().getDefaultDisplay().getWidth();
            // 设置SelectPicPopupWindow的View
            this.setContentView(conentView);
            // 设置SelectPicPopupWindow弹出窗体的宽
            this.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
            // 设置SelectPicPopupWindow弹出窗体的高
            this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            // 设置SelectPicPopupWindow弹出窗体可点击
            this.setFocusable(true);
            this.setOutsideTouchable(true);
            // 刷新状态
            this.update();
            // 实例化一个ColorDrawable颜色为半透明
            ColorDrawable dw = new ColorDrawable(0000000000);
            // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
            this.setBackgroundDrawable(dw);
            // mPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
            // 设置SelectPicPopupWindow弹出窗体动画效果
            //this.setAnimationStyle(R.style.AnimationPreview);
        }

        public void showPopupWindow(View parent) {
            if (!this.isShowing()) {
                this.showAsDropDown(parent, parent.getWidth(), 0);
            } else {
                this.dismiss();
            }
        }

        public void setListener() {

            att_ll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    setAttenService();
                    if (opflag.equals("0")) {
                        att_text.setText("取消关注");
                        att_iv.setImageDrawable(getResources().getDrawable(R.mipmap.quguan_ct));
                        opflag = "1";
                    } else {
                        att_text.setText("关注");
                        att_iv.setImageDrawable(getResources().getDrawable(R.mipmap.guanzhu_ct));
                        opflag = "0";
                    }
                }
            });
            save_contact.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    morePopWindow.dismiss();
                    bottomPopupOption.showPopupWindow();
                }
            });
            share_contact.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    morePopWindow.dismiss();
                    //share_dialog();
//                    umShareUtil.share_dialog(contactName.getText().toString(),
//                            contactPho.getText().toString(), contactEmail.getText().toString(),
//                            contactDept.getText().toString());

                    String msg = "姓名：" + contactName.getText().toString() + "\n" +
                            "手机：" + contactPho.getText().toString() + "\n" +
                            "邮箱：" + contactEmail.getText().toString() + "\n" +
                            "部门：" + contactDept.getText().toString();
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
                    intent.putExtra(Intent.EXTRA_TEXT, msg);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    startActivity(Intent.createChooser(intent, getTitle()));

//                    Intent intent = new Intent(Intent.ACTION_SEND);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    //intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("sdcard/1.png")));  //传输图片或者文件 采用流的方式
//                    intent.putExtra(Intent.EXTRA_TEXT, "分享分享微博");   //附带的说明信息
//                    intent.putExtra(Intent.EXTRA_SUBJECT, "标题");
//                    intent.setType("image/*");   //分享图片
//                    startActivity(Intent.createChooser(intent,"分享"));
                }
            });
            change_number.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    morePopWindow.dismiss();
                    dialog();
                }
            });

            bottomPopupOption.setItemClickListener(new BottomPopupOption.onPopupWindowItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    switch (position) {
                        case 0:
                            contactsUtilCt.toContactsEdit(true, contactName.getText().toString(),
                                    contactPho.getText().toString(), contactTel.getText().toString(), contactEmail.getText().toString(),
                                    contactDept.getText().toString());
                            break;
                        case 1:
                            contactsUtilCt.toContactsEdit(false, contactName.getText().toString(),
                                    contactPho.getText().toString(), contactTel.getText().toString(), contactEmail.getText().toString(),
                                    contactDept.getText().toString());
                            break;
                    }
                    bottomPopupOption.dismiss();
                }
            });
        }

        protected void dialog() {

            final View customLayout = getLayoutInflater().inflate(R.layout.change_number_layout_ct, null);
            final AlertDialog builder = new AlertDialog.Builder(ContactsDetailActivity_ct.this).create();
            edit_phone_number = (EditText) customLayout.findViewById(R.id.edit_phone_number);
            edit_tel_number = (EditText) customLayout.findViewById(R.id.edit_tel_number);
            edit_phone_number.setText(contactPho.getText().toString().trim());
            edit_tel_number.setText(contactTel.getText().toString().trim());
            TextView btn_cancel_1 = (TextView) customLayout.findViewById(R.id.btn_cancel_1);
            TextView btn_comfirm_1 = (TextView) customLayout.findViewById(R.id.btn_comfirm_1);
            btn_comfirm_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String phone_number = edit_phone_number.getText().toString();
                    String tel_number = edit_tel_number.getText().toString();
                    // 是空格
                    if (phone_number.trim().equals("") && tel_number.trim().equals("")) {
                        Toast.makeText(ContactsDetailActivity_ct.this, "请输入号码！", Toast.LENGTH_SHORT).show();
                        builder.dismiss();
                    } else {
                        if (!phone_number.trim().equals("")) {
                            if (CommonUtil.isChinaPhoneLegal(phone_number, "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$")) {
                                contactPho.setText(phone_number);
                                contactTel.setText(tel_number);
                            } else {
                                Toast.makeText(ContactsDetailActivity_ct.this, "输入的手机号码不符合规范！", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        } else {
                            contactPho.setText(phone_number);
                            contactTel.setText(tel_number);
                        }
                        builder.dismiss();
//                        callServiceForChangeIcon("");
                    }
                }
            });

            btn_cancel_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    builder.dismiss();
                }
            });
            builder.setView(customLayout);
            builder.show();
        }


    }

    private final int openPhotos = 6666;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case CROP_REQUEST_CODE5:
                if (data == null) {
                    return;
                }
                //将Uri图片转换为Bitmap
                try {
                    Bitmap photo;
                    photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));
//  Bitmap photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(data.getData()));
                    dataString = CameraAndAlbumUtil_ct.bitmapToString(photo);
                    // 保存修改后的图像
                    callServiceForChangeIcon(dataString);
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtils.e(e);
                    showMessage(e.getMessage());
                }
                break;
            case CAMERA_REQUEST_CODE:
                //判断是否直接点击了返回或取消按钮
                if (resultCode == Activity.RESULT_CANCELED) {
                    return;
                } else {
                    if (MobUtils.isExistSDCard()) {
                    }
                    if (isSurpass7Version()) {
                        File picture = new File(Environment.getExternalStorageDirectory(), "temp.jpg");

                        uritempFile = CameraAndAlbumUtil_ct.startCrop5(picture, ContactsDetailActivity_ct.this);
                    } else {
                        uritempFile = CameraAndAlbumUtil_ct.startCrop5(uritempFile, ContactsDetailActivity_ct.this);
                    }
                }

                break;
            case CROP_REQUEST_CODE:
                if (data == null) {
                    return;
                }
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");  // 没切图
                    dataString = CameraAndAlbumUtil_ct.bitmapToString(photo);
                    // 保存修改后的图像
                    callServiceForChangeIcon(dataString);
                }
                break;
            case openPhotos: // 更换头像
                if (data == null) {
                    return;
                }
                Uri uri = data.getData();
                uritempFile = CameraAndAlbumUtil_ct.startCrop5(uri, ContactsDetailActivity_ct.this);
                break;
        }
    }

    /**
     * 保存修改后的图像
     *
     * @param dataString
     */
    private void callServiceForChangeIcon(final String dataString) {

        try {
            JSONObject json = new JSONObject();
            json.put("transtype", Constant.TRANSTYPE_UPLOAD_IMAGE);
            json.put("psn_image", dataString); // 需要保存的图片
            json.put("user_code", getUserInfoLRY().getUser_code());
            json.put("tenant_id", getUserInfoLRY().getTenant_id());
            json.put("uuidToken", Constant.TOKEN);
            if (!CommonUtil.isNetworkConnected(this)) {
                CommonUtil.showToast(this, "当前网络不可用,修改未生效!");
                return;
            }
            MAServices_lib.callMACommonService(this, new ServiceCallback() {
                @Override
                public void execute(JSONObject json) {
                    LogUtils.e(json);
                    // 有错误的时候
                    if ("0".equals(json.optString("code"))) {
                        String msg = json.optString("message");
                        showMessage(msg);
                        return;
                    }

                    if (!dataString.equals("")) {
                        // 用户头像
                        url = json.opt("url") + "";
                        ChangeHeadImgObserverUtilTD.getInstance().notifyAllObserver(url);
                        // 修改用户信息对象
                        UserInfoLRY userInfo3 = readLocationObject(Constant.userInfoLry, UserInfoLRY.class);
                        userInfo3.setHead_image_url(url);
                        // 写记录用户信息
                        writeLocationObject(Constant.userInfoLry,
                                userInfo3);
                       /* Glide.with(ContactsDetailActivity_ct.this).load(url)
                                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                                .transform(new GlideCircleTransform_ct(ContactsDetailActivity_ct.this))
                                .into(iconIV);*/
                    }
                    File picture = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
                    if (picture.exists()) {// 删掉临时头像
                        picture.delete();
                    }
                }

                @Override
                public void error(String arg0, String arg1) {
                    Toast.makeText(ContactsDetailActivity_ct.this, arg0 + arg1,
                            Toast.LENGTH_LONG).show();
                }
            }, json);
        } catch (Exception e) {
            LogUtils.e(e);
            showMessage(e.getMessage());
        }
    }
}

